<style src="../../style/statistics.css" scoped></style>
<template>
    <div class="containerTable">
        <Row class="divSearch">
            <!--搜索框-->
                <Col span="18" >
                    <label class="searchLabel">所属地区:</label>
                    <Select v-model="searchModel.AreaCode"  placeholder="请选择..." class="searchInput" @on-change="GetData()">
                        <Option :value="userInfo.AreaCode">{{(userInfo.AreaCode=='530000000000')?'全省':'全市（州）'}}</Option>
                        <Option :value="item.value" v-for="item in AreaList" :key="item.value">{{item.label}}</Option>
                    </Select>                              
                    <label class="searchLabel">填报年度:</label>
                    <Select v-model="searchModel.FillInYear" placeholder="全部" :label-in-value="true" @on-change="GetData()" class="searchInput">
                        <!-- <Option value="">全部</Option> -->
                        <Option :value="item.DictValue" v-for="item in yearList" :key="item.DictValue">{{item.DictText}}</Option>
                    </Select>
                    <label class="searchLabel">季度:</label>
                    <Select v-model="searchModel.TimesCycle" placeholder="全部" :label-in-value="true" @on-change="GetData()" class="searchInput">                        
                        <Option :value="item.DictValue+'季度'" v-for="item in seasonList" :key="item.DictText">{{item.DictText}}</Option>
                    </Select>
                    <label class="searchLabel">水果种类:</label>
                    <Select v-model="searchModel.VarietyCode" placeholder="全部" :label-in-value="true" @on-change="VarietyChange" class="searchInput"> 
                        <Option value="">全部</Option>                    
                        <Option :value="item.VarietyCode" v-for="item in VarietyList" :key="item.VarietyCode">{{item.Variety}}</span></Option>
                    </Select>
                    <Button icon="ios-search" type="ghost" @click="GetData()" >查询</Button>
              </Col>
              <Col span="6" class="searchRight">                                       
                     <RadioGroup v-model="currentButton" @on-change="changeButton" type="button" >
                        <Radio label="listShow" title="列表">列表<Icon type="ios-paper" size="10"></Icon></Radio>                            
                        <Radio label="barShow" title="柱状图">柱状图<Icon type="stats-bars" size="10"></Icon></Radio>
                        <Radio label="mapShow" title="地图">地图<Icon type="android-map" size="10"></Icon></Radio>                            
                    </RadioGroup>                    
              </Col>     
            </Row> 
            <Row class="divSearch">
                <Col span="24" class="searchRight">
                    <!-- <Button type="success" @click="toAlertCheckResult()" class="searchButtonLeft">数据检测</Button>   -->
                    <label class="searchLabel">请选择导出类型:</label>
                    <Select v-model="searchModel.downType"  :label-in-value="true" class="searchInput"> 
                        <Option value="1">导出地区列表</Option>                    
                        <Option value="2">导出类型列表</Option>
                    </Select>
                    <Button style="margin-left:10px;" type="primary" v-show="listShow" @click="Download(searchModel.AreaCode)">导出列表</Button> 
                </Col>                                            
            </Row>            
            <Row  v-show="listShow" class="divStatis">
            <!-- 列表-->
                <table class="statisTable">
                  <thead>
                    <tr>
                      <th style="width:210px" rowspan="2">{{(searchModel.VarietyCode=="")?'种类':'地区'}}</th>
                      <th colspan="2">面积（亩）</th>
                      <th colspan="1">产量（吨）</th>
                      <th rowspan="2">本季度新植面积（亩）</th>                      
                    </tr>
                    <tr>
                      <th>在园水果面积</th>
                      <th>已收获面积</th>
                      <th>已收获产量</th>
                    </tr>
                  </thead>
                  <tbody :style="{height:clientHeight+'px'}">
                    <tr v-for="(dataModel,index) in datalist" :key="index" :style="rowStyle(index,datalist.length)">
                      <td v-if="dataModel.ParentCode" v-show="searchModel.VarietyCode==''" style="text-align:right;width:210px">{{dataModel.Variety}}</td> 
                      <td v-else v-show="searchModel.VarietyCode==''" style="font-weight:bold;text-align:center;width:210px">{{dataModel.Variety}}</td>
                      <td v-show="searchModel.VarietyCode!=''" style="text-align:center;width:210px">{{dataModel.AreaName}}</td>
                      <td>{{(dataModel.ZyArea)?FormatBigNum(dataModel.ZyArea.toFixed(1)):''}}</td>
                      <td>{{(dataModel.YshArea)?FormatBigNum(dataModel.YshArea.toFixed(1)):''}}</td>
                      <td>{{(dataModel.YshYield)?FormatBigNum(dataModel.YshYield.toFixed(1)):''}}</td>
                      <td>{{(dataModel.AddArea)?FormatBigNum(dataModel.AddArea.toFixed(1)):''}}</td>
                    </tr>
                  </tbody>
                </table>
         </Row>
         <Row v-show="barShow">
            <!--饼图-->
            <div  id="divBar" style="border:1px solid #D7DDE4;">柱状图</div>
        </Row>
        <Row  v-show="mapShow">
            <!--地图展示-->
            <div id="divMap"  style="border:1px solid #D7DDE4;">地图</div>
        </Row>
    </div>
</template>
<script>
import echarts from "echarts";
export default {
  data() {
    return {
      chartStyle:{height:(window.innerHeight - 220)+'px',width:(window.innerWidth - 250)+'px'},
      currentButton: "listShow",
      listShow: true, //列表显示控制器
      barShow: false, //柱状图显示控制器
      mapShow: false, //地图显示控制器      
      userInfo: this.GetlocaStorage("fruuserinfo"),
      AreaList: this.SearchAreaList(this.GetlocaStorage("fruuserinfo").AreaCode),//所属行政区划数组,
      yearList: this.GetGroupDict("ReportYear"), //周期
      seasonList: this.GetGroupDict("QuarterCycleValue"), //季节类型列表
      statusList: this.GetGroupDict("ReportStatus"), //报表状态类型列表
      VarietyList:[],
      fruitName:'水果',
      datalist:[],
      //柱状图和地图数据
      CurrentAreaName:'',
      xlist:[],//柱状图x轴分类数组
      zyArealist:[],
      yshArealist:[],
      yshYieldlist:[],
      addArealist:[],
      barList:[],
      MzyArealist:[],
      MyshArealist:[],
      MyshYieldlist:[],
      MaddArealist:[],
      mapList:[],
      dataModel: {
        //编辑模型
        Id: 0,
        ReportId: "",
        Variety: "",
        ZyArea: "",
        YshArea: "",
        YshYield: "",
        AvgPrice: "",
        AddArea: ""
      },
      clientHeight: window.innerHeight - 260, //表格默认高度
      //查询模型：根据需求删除不不要查询条件
      searchModel: {
        Id: "",
        ReportId: "",
        VarietyCode: "",
        Variety:'',
        ZyArea: "",
        YshArea: "",
        YshYield: "",
        AvgPrice: "",
        AddArea: "",
        downType:'1',
        ReportCode: "FruProSeason",
        FillInYear: new Date().getFullYear() + "",
        TimesCycle: '1季度',
        AreaCode: this.GetlocaStorage("fruuserinfo").AreaCode,
        Status: "",
        PageNumber: 1,
        PageSize: 20
      },
      pageSizeOpts: [20, 40, 50], //默认分页最大设置
      datas: {}, //table数据对象
      dataIds: [],
      ctx: this, //table数据上下文
      columnsList: []
    }
  },
  mounted() {
    //table高度计算方法
    const that = this;
    window.onresize = () => {
      return (() => {
        that.clientHeight = window.innerHeight - 260;
      })();
    };
  },
  methods: {
    rowStyle(index,length){  
      let striprow ={ backgroundColor: '#ebf7ff'};      
      if(index==(length-1)){       
        return {
             backgroundColor: '#f9c912'
          }
      }
      else if(index%2 !=0){
        return striprow;
      }
      else{        
        return 
      }
    },
    changeButton(n){
            if(n=="listShow")
            {
                this.listShow=true;//显示列表
                this.barShow=false;
                this.mapShow=false;
            }
            else if(n=="barShow")
            {
                this.listShow=false;
                this.barShow=true;//显示饼图
                this.mapShow=false;
                //this.showBar();
            }
             else if(n=="mapShow")
            {
                this.listShow=false;
                this.barShow=false;//显示地图
                this.mapShow=true;
                //  this.getStatsData();   //获取地区统计数据  
                //this.showMap();
                if(!this.searchModel.VarietyCode)
                this.searchModel.VarietyCode='sum';
            }
            else{
                 this.listShow=true;//默认显示列表
                 this.barShow=false;
                 this.mapShow=false;
            }
        },
    showBar() {
      var self = this;
      //显示柱状图
      var self=this;
      var containerBar=document.getElementById('divBar');
      var containerTable=document.getElementsByClassName('ivu-col ivu-col-span-4');
       //用于使chart自适应高度和宽度,通过窗体高宽计算容器高宽
      var resizeContainerBar = function () {
          //containerTable[0].clientWidth 左侧菜单栏的宽度
          containerBar.style.width = (window.innerWidth- containerTable[0].clientWidth-20)+'px';
          containerBar.style.height = (window.innerHeight-250)+'px';
      };
      //设置容器高宽
      resizeContainerBar();
      var myBar = myEcharts.init(containerBar, 'shine');
      var BarName=this.searchModel.FillInYear+'年(一)'+self.CurrentAreaName + self.fruitName+ self.searchModel.TimesCycle+'生产情况表';
      var echartsItem=['在园面积','已收获面积','已收获产量','本季度新植面积'];
      self.barList = [];
      self.barList.push(self.zyArealist,self.yshArealist,self.yshYieldlist,self.addArealist);
      var optionBar = self.GetBarOption(BarName,self.xlist,echartsItem,self.barList);
      myBar.setOption(optionBar);
      window.onresize = function () {
          //重置容器高宽
          resizeContainerBar();
          myBar.resize();
      };
    },
    showMap(){
      //******************显示地图
      var self=this;
      var mapType;
       //判断当前用户是否为省级账号
      if(self.userInfo.AreaCode=="530000000000")
      {
          // self.isProvince=true;
          mapType=self.searchModel.AreaCode;
      }
      else{
          mapType=self.userInfo.AreaCode;
      }
      var containerMap=document.getElementById('divMap');
      var containerTable=document.getElementsByClassName('ivu-col ivu-col-span-4');
      // //用于使chart自适应高度和宽度,通过窗体高宽计算容器高宽
      var resizeContainerMap = function () {
          //containerTable[0].clientWidth 左侧菜单栏的宽度
          containerMap.style.width = (window.innerWidth- containerTable[0].clientWidth-20)+'px';
          containerMap.style.height = (window.innerHeight-230)+'px';
      };
      //设置容器高宽
      resizeContainerMap();

      var myMap = myEcharts.init(containerMap, 'shine');
      var MapName=this.searchModel.FillInYear+'年(一)'+self.CurrentAreaName+ self.fruitName+ self.searchModel.TimesCycle+'生产情况表';
      
      var GeoData=self.GetGeoData(mapType); 
      var echartsItem=['在园面积','已收获面积','已收获产量','本季度新植面积'];
      self.mapList = [];
      self.mapList.push(self.MzyArealist,self.MyshArealist,self.MyshYieldlist,self.MaddArealist);
      var optionMap = self.GetMapOption(MapName,GeoData,mapType,echartsItem,self.mapList);
      myMap.setOption(optionMap);
      //用于使chart自适应高度和宽度
      window.onresize = function () {
          //重置容器高宽
          resizeContainerMap();
          myMap.resize();
      };
    },
        // getVariety(){
        //     for(let i=0;i<this.VarietyList.length;i++){
        //         if(this.searchModel.VarietyCode == this.VarietyList[i].VarietyCode){
        //             if(this.searchModel.VarietyCode != 'sum'){
        //                 return this.VarietyList[i].Variety
        //             }else{
        //                 return '全部水果'
        //             }
        //         }
        //     }
        //     this.searchModel.Variety=Variety;
        //     return this.searchModel
        // },
        getVarietyDic(){
            var self = this;            
            this.$http.get('FruProSeason/GetVarietyDic',).then(function(res){
                if(res.data.status==1){
                    self.VarietyList = res.data.model;
                }
                else{
                    self.$Modal.error({title:'提示信息',content:res.data.message});
                }
            })
        },
        Download(){  
            //this.getVariety();          
            window.open(this.$http.defaults.baseURL + "FruProSeason/GetStatisExcel?FillInYear="  + this.searchModel.FillInYear + "&&AreaCode=" + this.userInfo.AreaCode+
            "&&TimesCycle="+this.searchModel.TimesCycle+"&&DownType="+this.searchModel.downType);
        },
        getListData(){
            var self = this;
            let model = new Object();
            model.AreaCode = this.searchModel.AreaCode;
            model.FillInYear = this.searchModel.FillInYear;
            model.VarietyCode = this.searchModel.VarietyCode;  
            model.TimesCycle = this.searchModel.TimesCycle ; 
            self.xlist=[]; 
            self.zyArealist=[];
            self.yshArealist=[];
            self.yshYieldlist=[];
            self.addArealist=[];  
            self.MzyArealist=[];
            self.MyshArealist=[];
            self.MyshYieldlist=[];
            self.MaddArealist=[];   
            this.$http.get('FruProSeason/GetStatisListData',{params:model}).then(function(res){
                if(res.data.status==1){
                    self.datalist = res.data.model;
                    self.CurrentAreaName=self.datalist[self.datalist.length-1].AreaName=="合计"||!self.datalist[self.datalist.length-1].AreaName?'云南省':self.datalist[self.datalist.length-1].AreaName;
                    for(let i = 0;i<self.datalist.length-1;i++){
                      let item = self.datalist[i];
                        if(self.searchModel.VarietyCode == ""){
                          self.xlist.push(item.Variety);
                        }else{
                          self.xlist.push(item.AreaName);
                        }            
                      self.zyArealist.push(item.ZyArea);
                      self.yshArealist.push(item.YshArea);
                      self.yshYieldlist.push(item.YshYield);
                      self.addArealist.push(item.AddArea);
                      //地图数据
                      self.MzyArealist.push({'name':item.AreaName,'value':item.ZyArea});
                      self.MyshArealist.push({'name':item.AreaName,'value':item.YshArea});
                      self.MyshYieldlist.push({'name':item.AreaName,'value':item.YshYield});
                      self.MaddArealist.push({'name':item.AreaName,'value':item.AddArea});
                    }
                    self.showBar();
                    self.showMap();
                }
                else{
                    self.$Modal.error({title:'提示信息',content:res.data.message});
                }
            })
        },
        GetData(){          
            this.getListData();           
        },
        VarietyChange(obj){
          var lable = obj.label;
          this.fruitName = (lable=='全部'||lable=='合计')?'水果':lable;
          this.GetData();
        },
         //数据检测
    checkData(){
     let templist = this.datalist;
     let message = '';
     let isOk = true;//数据无误
     let sumObj = templist[templist.length-1];//合计栏数据
     let totalModel = new Object();
     totalModel.ZyArea = 0;
     totalModel.YshArea = 0;
     totalModel.YshYield = 0;
     totalModel.AddArea = 0;  
     for(let i = 0;i < templist.length;i++){
       let item  = templist[i];
       let parentModel = new Object();
       parentModel.ZyArea = 0;
       parentModel.YshArea = 0;
       parentModel.YshYield = 0;
       parentModel.AddArea = 0; 
       parentModel.hasChild = false; 
       for(let j = 0;j < templist.length;j++){
        let sonItem = templist[j];        
        if(sonItem.ParentCode == item.VarietyCode){
          parentModel.hasChild = true;
          if(sonItem.ZyArea){
            parentModel.ZyArea += sonItem.ZyArea;
          }
          if(sonItem.YshArea){
            parentModel.YshArea += sonItem.YshArea;
          }
          if(sonItem.YshYield){
            parentModel.YshYield += sonItem.YshYield;
          }
          if(sonItem.AddArea){
            parentModel.AddArea += sonItem.AddArea;
          }
        }
       }
       if(parentModel.hasChild){       
       if(item.ZyArea && parentModel.ZyArea > item.ZyArea){         
         isOk = false;
         message += item.Variety+'的在园面积不能小于其子项之和！</br>';        
       }
       if(item.YshArea && parentModel.YshArea > item.YshArea){
         isOk = false;
         message += item.Variety+'的已收获面积不能小于其子项之和！</br>';
       }
       if(item.YshYield && parentModel.YshYield > item.YshYield){
         isOk = false;
         message += item.Variety+'的已收获产量不能小于其子项之和！</br>';
       }
       if(item.AddArea && parentModel.AddArea > item.AddArea){
         isOk = false;
        message += item.Variety+'的季度新增面积不能小于其子项之和！</br>';
       }   
       }    
       if(item.VarietyCode !='sum'&& !item.ParentCode){        
         if(item.ZyArea){
           totalModel.ZyArea += item.ZyArea;
         }
         if(item.YshArea){
           totalModel.YshArea += item.YshArea;
         }
         if(item.YshYield){
           totalModel.YshYield += item.YshYield;
         }
         if(item.AddArea){
           totalModel.AddArea += item.AddArea;
         }
       }
     }

     if(sumObj.ZyArea && (totalModel.ZyArea-sumObj.ZyArea < -1||totalModel.ZyArea-sumObj.ZyArea>1)){       
       isOk = false;
       message += '合计栏的在园面积计算错误！</br>';
     }
     if(sumObj.YshArea && (totalModel.YshArea-sumObj.YshArea < -1||totalModel.YshArea-sumObj.YshArea >1)){
       isOk = false;
       message += '合计栏的已收获面积计算错误！</br>';
     }
     if(sumObj.YshYield && (totalModel.YshYield-sumObj.YshYield < -1||totalModel.YshYield-sumObj.YshYield >1)){
       isOk = false;
       message += '合计栏的已收获产量计算错误！</br>';
     }
     if(sumObj.AddArea && (totalModel.AddArea-sumObj.AddArea < -1||totalModel.AddArea-sumObj.AddArea > 1)){
       isOk = false;
       message += '合计栏的季度新增面积计算错误！</br>';
     }
     if(isOk){
       message += '数据检测无误！';
     }
     return message;
    },
    toAlertCheckResult(){ 
      var message  = this.checkData();         
      this.$Modal.warning({
        title:'提示信息',
        content:message
      });
    },
      CurrentSeason(){
      var self = this;
      let currentMonth = new Date().getMonth()+1;      
      if(currentMonth >= 2 &&currentMonth <= 5){
        self.searchModel.TimesCycle = "1季度";
      }
      else if(currentMonth >= 6&&currentMonth <= 8){
        self.searchModel.TimesCycle = "2季度";
      }
      else if(currentMonth >= 9&&currentMonth <= 11){
        self.searchModel.TimesCycle = "3季度";
      }
      else{
        self.searchModel.TimesCycle = "4季度";
      }
    },
    currentYear() {
      let year = new Date().getFullYear();
      let month = new Date().getMonth();
      if (month > 1) {
        this.searchModel.FillInYear = year.toString();
      } else {
        this.searchModel.FillInYear = (year - 1).toString();
      }
    }
  },
  //创建Vue页面方法
  created: function() {
    this.currentYear();
    this.CurrentSeason();
    this.getVarietyDic();
    this.GetData();
  },
  watch: {
    //需要监听的在此处新增监听对象
  }
};
</script>
